package com.sbr.seb.wicket.page;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sbr.seb.entity.livraison.Application;
import com.sbr.seb.entity.planning.DemandeDeLivraison;
import com.sbr.seb.entity.planning.DemandeState;
import com.sbr.seb.entity.planning.Environnement;
import com.sbr.seb.entity.planning.Month;
import com.sbr.seb.entity.planning.ProjectCalendar;
import com.sbr.seb.entity.planning.Week;
import com.sbr.seb.planning.PlanningService;
import com.sbr.seb.planning.dao.ApplicationDao;
import com.sbr.seb.wicket.util.PlanningUtil;

/**
 * Homepage
 */
public class Planning extends BasePage {

	private static final Logger logger = LoggerFactory.getLogger(Planning.class);


	//	private String monthChoice = "0";
	private Month month;

	private String projectName;
	private DemandeDeLivraison demande;

	private List<String> dayNames = new ArrayList<String>(31);
	//	private Integer[] dayNumbers = new Integer[31];
	private List<Integer> dayNumbers = new ArrayList<Integer>(31);
	private List<Week> weekList = new ArrayList<Week>();

	@SpringBean
	private ApplicationDao applicationDao;

	@SpringBean
	private PlanningService planningService;

	public Planning() {
		super();
		demande = new DemandeDeLivraison();
		if (month == null) {
			month = Month.JANUARY;
		}
		weekList = PlanningUtil.createWeekList(weekList, month);
		dayNames = PlanningUtil.createDayNames(dayNames, month);
		dayNumbers = PlanningUtil.createDayNumber(dayNumbers,month);
		logger.debug("####################################################### month = "+month);
		//		month = Month.values()[Integer.parseInt(monthChoice)];
		final PlanningPanel panel = new PlanningPanel("planning", applicationDao, planningService);
		panel.setOutputMarkupId(true);


		//    	IColumn[] columns = new IColumn[weekList.size()];
		//        
		//    	for (IColumn column : columns) {
		//    		column = new PropertyColumn(new Model("bla"), "name.first", "name.first");
		//    	}
		//		IColumn[] columns = new IColumn[2];
		//		columns[0] = new PropertyColumn(new Model("First Name"), "name.first", "name.first");
		//		columns[1] = new PropertyColumn(new Model("Last Name"), "name.last", "name.last");
		//
		//		final UserProvider userProvider = new UserProvider();
		//
		//		DefaultDataTable table = new DefaultDataTable("datatable", columns, userProvider, 10);
		//
		//		add(table);



		Form monthForm = new Form("monthChange");

		final DropDownChoice<Month> monthChoice = new DropDownChoice<Month>("month", new PropertyModel(this, "month"), Arrays.asList(Month.values()),new ChoiceRenderer<Month>("name","number")) {
			//			@Override
			//			protected boolean wantOnSelectionChangedNotifications() {
			//				return true;
			//			}
			//			
			//			@Override
			//			protected void onSelectionChanged(final Month newSelection) {
			//                month = newSelection;
			//            }
		};
		monthChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				logger.debug("onUpdate "+month.getName());
				weekList = PlanningUtil.createWeekList(weekList, month);
				dayNames = PlanningUtil.createDayNames(dayNames, month);
				dayNumbers = PlanningUtil.createDayNumber(dayNumbers,month);
				target.addComponent(panel);
			}

		});

		monthForm.add(monthChoice);

		panel.add(monthForm);

		add(panel);

		Form planningForm = new Form("planningForm") {

			@Override
			protected void onSubmit() {
				logger.info("onSubmit called");
				logger.info("Ajout d'une demande "+demande);
				demande.setDemandeState(DemandeState.ENCOURS);
				planningService.addDemandeDeLivraison(demande);
			}
		};
		final DropDownChoice<Application> projectBox = new DropDownChoice<Application>("projectBox", new PropertyModel(demande,"application"), new LoadableDetachableModel<List<Application>>(){
			@Override
			protected List<Application> load() { 
				return applicationDao.findAll();
			}
		},  new ChoiceRenderer<Application>("name", "id"));

		final TextField<Object> projectVersion = new RequiredTextField("projectVersion", new PropertyModel(demande.getApplication(), "version"));
		final TextField<Object> semaineDemandee = new RequiredTextField("semaineDemandee", new PropertyModel(demande, "deliveryWeek"));
		final DropDownChoice<Environnement> envBox = new DropDownChoice<Environnement>("environnementBox", new PropertyModel(demande, "environnement"), Arrays.asList(Environnement.values()),  new ChoiceRenderer<Environnement>("name","name"));

		planningForm.add(projectBox);
		planningForm.add(projectVersion);
		planningForm.add(semaineDemandee);
		planningForm.add(envBox);

		add(planningForm);
		add(new FeedbackPanel("feedbackPanel"));

	}

	public void setApplicationDaoDao(ApplicationDao applicationDao) {
		this.applicationDao = applicationDao;
	}



	public void setMonth(Month month) {
		logger.debug("setter of month called"); // ce setter est inutile !! TODO le suuprimer
		this.month = month;
	}

	class PlanningPanel extends WebMarkupContainer {

		private ApplicationDao applicationDao;
		private PlanningService planningService;


		public void setApplicationDaoDao(ApplicationDao applicationDao) {
			this.applicationDao = applicationDao;
		}


		public PlanningPanel(String id, ApplicationDao applicationDao, PlanningService planningService) {
			super(id);
			this.applicationDao = applicationDao;
			logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> CONSTRUCTING PLANNINGPANEL");
			List<Application> applicationList = applicationDao.findAll();

			//			final RepeatingView view = new RepeatingView("repeater");
			final ListView<Week> dayRepeater = new ListView<Week>("repeater", weekList) {
				@Override
				protected void populateItem(ListItem<Week> item) {

					logger.debug("populateItem of repeater ");
					Week week = item.getModelObject();
					Label label = new Label("weekNumber", "S"+week.getNumber());
					logger.debug("number of day displaying "+week.getNumberOfDay());
					item.add(new SimpleAttributeModifier("colspan", week.getNumberOfDay()));
					item.add(label);
				}

			};
			//			for (Week week : weekList) {
			//				Label label = new Label(week.getNumber(), "S"+week.getNumber());
			//				label.add(new SimpleAttributeModifier("colspan", week.getNumberOfDay()));
			//				view.add(label);
			//			}
			add(dayRepeater);


			//			final RepeatingView dayRepeater = new RepeatingView("dayNameRepeater");
			final ListView<String> dayNameRepeater = new ListView<String>("dayNameRepeater", dayNames) {
				@Override
				protected void populateItem(ListItem<String> item) {

					logger.debug("populateItem of dayNameRepeater ");
					String dayName = item.getModelObject();
					Label label = new Label("dayName", dayName);
					if (dayName.equals(" ")) {
						label.add(new SimpleAttributeModifier("bgcolor","#c0c0c0"));
					}
					item.add(label);
				}

			};
			//			int i = 0;
			//			for (String dayName : dayNames) {
			//				Label label = new Label(String.valueOf(i++), dayName);
			//				if (dayName.equals(" ")) {
			//					label.add(new SimpleAttributeModifier("bgcolor","#c0c0c0"));
			//				}
			//
			//				dayRepeater.add(label);
			//			}
			add(dayNameRepeater);

			//			final RepeatingView dayNumberRepeater = new RepeatingView("dayNumberRepeater");
			final ListView<Integer> dayNumberRepeater = new ListView<Integer>("dayNumberRepeater", dayNumbers) {
				@Override
				protected void populateItem(ListItem<Integer> item) {

					logger.debug("populateItem of dayNumberRepeater ");
					Integer dayNumber = item.getModelObject();
					Label label = new Label("dayNumber", String.valueOf(dayNumber));
					item.add(label);
					logger.debug("dayNumbers size = "+dayNumbers.size());
				}

			};

			//			for (int dayNumber : dayNumbers) {
			//				Label label = new Label(String.valueOf(dayNumber), String.valueOf(dayNumber));
			//				dayNumberRepeater.add(label);
			//			}
			add(dayNumberRepeater);

			List<DemandeDeLivraison> demandeList = planningService.findAllByMonth(month);
			//			List<ProjectCalendar> projectCalendarList = convertProject(applicationList, demandeList);

			final ListView<DemandeDeLivraison> projectView = new ListView<DemandeDeLivraison>("projectList", planningService.findAllByMonth(month)) {
				@Override
				protected void populateItem(ListItem<DemandeDeLivraison> item) {
					DemandeDeLivraison project = item.getModelObject();
					item.add(new Label("projectName", project.getApplication().getName()));
					RepeatingView projectRepeater = new RepeatingView("projectRepeater");
					//					ListView<Integer> projectRepeater = new ListView<Integer>("projectRepeater", Arrays.asList(dayNumbers)) {
					//
					//						@Override
					//						protected void populateItem(ListItem<Integer> item) {
					//							Integer dayNumber = item.getModelObject();
					//							Label label = new Label("dayNumber", " ");
					//							label.add(new SimpleAttributeModifier("bgcolor","#c0c0c0"));
					//							item.add(label);
					//						}
					//						
					//					};
					logger.debug("dayNumbers size = "+dayNumbers.size());
					for (int dayNumber : dayNumbers) {
						Label label = new Label(String.valueOf(dayNumber), " ");
						//						label.setEscapeModelStrings(false);
						//						logger.info(dayNumber+" OK = "+project.isADayOfDelevery(dayNumber));
						if (project.isDayOfDelivery(dayNumber)) {
							label.add(new SimpleAttributeModifier("bgcolor","green"));
						} else {
							label.add(new SimpleAttributeModifier("bgcolor","#c0c0c0"));
						}
						projectRepeater.add(label);
					}
					item.add(projectRepeater);
				}

			};
			add(projectView);
		}


		private List<ProjectCalendar> convertProject(List<Application> applicationList, List<DemandeDeLivraison> demandeLivraisonList) {
			List<ProjectCalendar> projetCalendarList = new ArrayList<ProjectCalendar>();
			ProjectCalendar projetCalendar = null;
			logger.info("convertProject "+applicationList.size());
			for (Application application : applicationList) {
				projetCalendar = new ProjectCalendar();
				// TODO faire un constructeur de copie
				projetCalendar.setId(application.getId());
				projetCalendar.setName(application.getName());
				Map<Integer, DemandeDeLivraison> demandeLivraisonListTemp = new HashMap<Integer, DemandeDeLivraison>();
				for (DemandeDeLivraison demande : demandeLivraisonList) {

					if (demande.getApplication().getId().equals(projetCalendar.getId())) {
						logger.info("convertProject = OK "+demande.getDeliveryWeek());
						demandeLivraisonListTemp.put(demande.getDeliveryWeek(), demande);
					}
				}
				//				projetCalendar.setDeliveryList(demandeLivraisonListTemp);
				projetCalendar.setDeliveryMap(demandeLivraisonListTemp);
				projetCalendarList.add(projetCalendar);
			}
			return projetCalendarList;
		}

	}

	public void setPlanningService(PlanningService planningService) {
		this.planningService = planningService;
	}

	public void setApplicationDao(ApplicationDao applicationDao) {
		this.applicationDao = applicationDao;
	}

}
